package com.killer.rpc;

import com.killer.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 自定义解码器,将字节数组编码成对应的对象
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Serializer serializer;
    private Class<?> clazz;

    public RpcDecoder(Serializer serializer,Class<?> clazz) {
        this.serializer=serializer;
        this.clazz=clazz;
    }

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //读取消息的长度
        int length = in.readInt();
        //如果可以读取的数据长度小于期望的消息长度，需要重置一下读的下标，重新读取
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[length];
        //将读取的字节填充到一个空的字节数组中
        in.readBytes(bytes);
        //将其反序列化成对象
        Object object = serializer.deserialize(clazz, bytes);
        //将其传递给下一个入站类处理
        out.add(object);
    }
}
